package phoenics.apeak.crawl;

import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.springframework.context.ApplicationContext;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.WorkHandler;

public class DocumentHandle implements EventHandler<Document>,WorkHandler<Document>{
	private HttpClient httpClient;
	private ApplicationContext applicationContext;
	public DocumentHandle(HttpClient httpClient){
		this.httpClient=httpClient;
	}
	public DocumentHandle(ApplicationContext applicationContext){
		this.applicationContext=applicationContext;
		this.httpClient=applicationContext.getBean(HttpClient.class);
	}
	public DocumentHandle(){
	}
	@Override
	public void onEvent(Document event) throws Exception {
		Request request=this.httpClient.newRequest(event.getUrl());
		request.idleTimeout(15, TimeUnit.SECONDS);
		request.timeout(15, TimeUnit.SECONDS);
		String agent=Document.getAgent();
		if(agent!=null && !agent.equals("")){
			request.agent(agent);
		} 
		if(event.getCookie()!=null){
			request.cookie(event.getCookie());
		}
		 request.send(event.takeListener(this.applicationContext));
		//System.out.println("DocumentHandle===="+event.getTag()+"=="+event.getIii().toString()+"===="+event.getIp());
	}

	@Override
	public void onEvent(Document event, long sequence, boolean endOfBatch) throws Exception {
		this.onEvent(event);
	}

}
